from apps.base.models import Department
from .forms import DepartmentAddForm, DepartmentEditForm
from service import res_json_data
from django.views.decorators.http import require_GET, require_POST


# /api/v1/department/treetable/
@require_GET
def get_list_as_treetable(request):
    def get_children(item):
        """递归获取子部门"""
        children = []
        for child in item.department_set.filter(is_deleted=False):  # 顶级部门:顶级部门所有子部门=1:n so,是反向查询
            child_data = child.json()
            child_data['children'] = get_children(child)  # 递归获取子部门
            children.append(child_data)
        return children

    first_queryset = Department.objects.filter(pid__isnull=True, is_deleted=False)  # 部门是自关联的 获取所有顶级部门(pid为null的部门)

    res_data = []
    for item in first_queryset:
        item_data = item.json()
        item_data['children'] = get_children(item)  # 递归获取子部门
        res_data.append(item_data)

    return res_json_data.table_api(data=res_data)


# /api/v1/department/add/
@require_POST
def department_add(request):
    # > 规则怪谈:
    # 1. 新增的部门的上级部门id需有效 - <字段自身>
    # 2. 新增的部门名不能跟已存在的部门名重名 - <视图函数中 or clean中皆可>
    form = DepartmentAddForm(request.POST)
    if not form.is_valid():
        return res_json_data.no_valid_api(form)
    name = form.cleaned_data.get('name')
    if Department.objects.filter(name=name, is_deleted=False).exists():
        msg = '该部门名称已存在,请重新填写!!'
        return res_json_data.summary_error_api(msg=msg)
    form.save()
    return res_json_data.success_api(msg='部门新增成功!')


# /api/v1/department/edit/
@require_POST
def department_edit(request):
    edit_id = request.POST.get('id')
    dep_obj = Department.objects.filter(id=edit_id, is_deleted=False).first()
    if not dep_obj:
        return res_json_data.not_found_api(msg="部门不存在或已删除!")

    # > 规则怪谈:
    # 1. 修改的上级部门id需有效 - <字段自身>
    # 2. 不能设置自己为父部门 - <视图函数中,便于拿到edit_id>
    # 3. 修改的部门名不能跟除自己以外的其他已存在的部门名重名 - <视图函数中,便于拿到edit_id>
    form = DepartmentEditForm(request.POST, instance=dep_obj)
    if not form.is_valid():
        return res_json_data.no_valid_api(form)

    name = form.cleaned_data.get('name')
    if Department.objects.exclude(id=edit_id).filter(name=name, is_deleted=False).exists():
        msg = '该部门名称已存在,请重新填写!!'
        return res_json_data.summary_error_api(msg=msg)

    pid_obj = form.cleaned_data.get('pid')
    if pid_obj and pid_obj.id == int(edit_id):
        msg = '不能选择自己作为父部门!!!'
        return res_json_data.summary_error_api(msg=msg)
    form.save()
    return res_json_data.success_api(msg='部门修改成功!')


# /api/v1/department/post/
@require_POST
def department_del(request):
    del_id = request.POST.get('id')
    dep_obj = Department.objects.filter(id=del_id, is_deleted=False).first()
    if not dep_obj:
        return res_json_data.not_found_api(msg="部门不存在或已删除!")

    # >规则怪谈: 若部门下有子部门,则不能删除
    if dep_obj.department_set.filter(is_deleted=False):
        return res_json_data.summary_error_api(msg="该部门下有子部门,不能删除!")
    dep_obj.is_deleted = True  # 标记为删除
    dep_obj.save()
    return res_json_data.success_api(msg='部门删除成功!')
